<template>
  <el-cascader
    class="comp-area-cascader"
    :options="options"
    v-model="areaModel"
    @click.native="chooseProvince"
    @active-item-change="chooseCityArea"
    @change="$emit('change', { value: areaModel, data: model })"
    :show-all-levels="showAllLevels"
  ></el-cascader>
</template>

<script>
import { ShaohuoPriceService } from 'services/Api'
import { mapState } from 'vuex'

export default {
  name: 'CompAreaCascader',
  data () {
    return {
      areaModel: [],
      options: [],
      chooseProvinceId: '',
      chooseCityId: '',
      provinceList: null, // 省份列表
      cityList: null, // 城市列表
      areaList: null // 区列表
    }
  },
  props: {
    metaData: {
      default: () => { return {} },
      type: Object
    }, // 初始数据
    model: Object,
    reset: Boolean,
    limitLevel: String, // province city
    showAllLevels: {
      default: false,
      type: Boolean
    }
  },
  watch: {
    reset (boo) {
      this.areaModel = []
    },
    metaData: {
      immediate: true,
      handler (v) {
        if (!v || !Object.keys(v).length) return
        if (v.provinces) {
          this.provinceHandler(v.provinces.data)
        }
        if (v.cities) {
          this.chooseProvinceId = v.cities.id
          this.cityHandler(v.cities.data)
        }
        if (v.model) {
          this.areaModel = v.model.map((id, index, model) => {
            if (index === model.length - 1) {
              const cities = this.options
                .find(i => i.value === this.chooseProvinceId)
                .children
              let target
              switch (index) {
                case 1:
                  target = cities
                    .find(i => i.value.region_id === id)
                    .value
                  break
                case 2:
                  target = cities
                    .find(i => i.value === this.chooseCityId)
                    .children
                    .find(i => i.value.region_id === id)
                    .value
              }
              id = target
            }
            return id
          })
        }
      }
    }
  },
  computed: {
    ...mapState([ 'acc_id' ]),
    // 获取省列表参数
    getAllProvinceParam () { return { acc_id: this.acc_id } },
    // 获取城市列表参数
    getCityByIdParam () {
      return {
        acc_id: this.acc_id,
        id: this.chooseProvinceId
      }
    },
    // 获取区列表参数
    getAreaByIdParam () {
      return {
        acc_id: this.acc_id,
        id: this.chooseCityId
      }
    }
  },
  methods: {
    // 选择省
    chooseProvince () {
      if (!this.provinceList) this.getAllProvinceApi()
    },
    // 选择市，区
    chooseCityArea (parent) {
      if (
        parent.length === 1 &&
        this.chooseProvinceId !== parent[0] &&
        this.limitLevel !== 'province'
      ) {
        // 选择市
        this.chooseProvinceId = parent[0]
        this.getCityByIdApi()
      } else if (
        parent.length === 2 &&
        this.chooseCityId !== parent[1] &&
        this.limitLevel !== 'city'
      ) {
        // 选择区
        this.chooseCityId = parent[1]
        this.getAreaByIdApi()
      }
    },
    // 获取省份列表接口
    async getAllProvinceApi () {
      const [ err, res ] = await ShaohuoPriceService.getAllProvince(this.getAllProvinceParam)
      if (err) return this.$message.error(err.message || '获取失败')
      this.provinceHandler(res)
    },
    provinceHandler (res) {
      res.shift()
      this.provinceList = res
      this.options = this.transformHandler(res, this.limitLevel !== 'province')
    },
    // 获取城市列表接口
    async getCityByIdApi () {
      const [ err, res ] = await ShaohuoPriceService.getCityAreaById(this.getCityByIdParam)
      if (err) return this.$message.error(err.message || '获取失败')
      this.cityHandler(res)
    },
    cityHandler (res) {
      res.shift()
      this.cityList = res
      this.options = this.options.map(option => {
        if (option.value === this.chooseProvinceId) option.children = this.transformHandler(res, this.limitLevel !== 'city')
        return option
      })
    },
    // 获取区列表接口
    async getAreaByIdApi () {
      const [ err, res ] = await ShaohuoPriceService.getCityAreaById(this.getAreaByIdParam)
      if (err) return this.$message.error(err.message || '获取失败')
      this.areaHander(res)
    },
    areaHander (res) {
      res.shift()
      this.areaList = res
      this.options = this.options.map(option => {
        if (option.value === this.chooseProvinceId) {
          option.children = option.children.map(child => {
            if (child.value === this.chooseCityId) child.children = this.transformHandler(res, false)
            return child
          })
        }
        return option
      })
    },
    transformHandler (list, hasChildren = true) {
      return list.map(item => {
        let o = { label: item.name, value: item.region_id, children: [] }
        if (!hasChildren) o = { label: item.name, value: item }
        return o
      })
    }
  }
}
</script>

<style lang="scss">
@import "src/styles/config/components.scss";

@include b(area-cascader) {}
</style>
